const mysql = require('mysql')
const fs = require('fs')
const config = JSON.parse(fs.readFileSync('./config/database.json', 'utf-8'))
module.exports = class {
  constructor() {

  }
  mysqlConnection(status = false) {
    return new Promise(resolve => {
      this.connection = mysql.createPool({
        host: config.mysql_host,
        port: 3306,
        database: config.mysql_database,
        user: config.mysql_user,
        password: config.mysql_password,
        connectionLimit: 50,
        acquireTimeout: 15000,
        waitForConnections: true,
        queueLimit: 0,
      });
      resolve()
    })
  }
  async execMysql(sql, status = false) {
    await this.mysqlConnection(status)
    return new Promise(resolve => {
      this.connection.getConnection((err, con) => {
        if (!err) {
          con.query(sql, async (err, result) => {
            con.release();
            if (err) {
              console.log(err);
              return;
            }
            const state = this.dataState(result);
            resolve(state);
          })
        }
      })
    })

  }
  dataState(state) {
    return JSON.parse(JSON.stringify(state));
  };
}
